/*  BlogBotSerialBridge.java Version 103 - 27th May 2008
 *  BlogBotSerialBridge.java reads data from the serial port
 *  See Versions for program version number
 *  Copyright (C) 2008  Andy Broomfield andy@newmediathinking.com
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/

package net.blogbotplatform.blogbot;

import java.io.*;
import java.util.*;
import gnu.io.*;

public class BlogBotSerialBridge implements SerialPortEventListener {
	//BlogBotPanel bbp;
	
	static CommPortIdentifier portId;
	static Enumeration portList;
	SerialPort serialPort = null;
	
	InputStream inputStream;
	OutputStream outputStream;

    int numBytes = 0;
    int serialValue;
    
    boolean portOpen = false;
	
	public BlogBotSerialBridge() {
		//bbp = parent;
		RXTXCommDriver driver = new RXTXCommDriver();
		driver.initialize();
	}
	
	public void openSerialPort(String portName, int baudRate) {
		
		portOpen = false; // set the portOpen flag as false
		
		System.out.println("Opening Port");
		portList = CommPortIdentifier.getPortIdentifiers();
		
		while (portList.hasMoreElements()) {
        		portId = (CommPortIdentifier) portList.nextElement();
       		if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
       			System.out.println("port found : " + portId.getName());
            		if (portId.getName().equals(portName)) {
            			try {
            				System.out.println("Opening Port " + portId.getName());
            				serialPort = (SerialPort) portId.open("BlogBotApp", 2000);
            			} catch (PortInUseException e) { 
            				System.out.println("Port in Use Expception" + e);
            			}
            			try {
            				System.out.println("intilizing input and output streams.");
            				inputStream = serialPort.getInputStream();
            				outputStream = serialPort.getOutputStream();
            			} catch (IOException e) {}
            			try {
            				serialPort.addEventListener(this);
            			} catch (TooManyListenersException e) {}
            				serialPort.notifyOnDataAvailable(true);
            			try {
            				serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
            				System.out.println("port open");
            				portOpen = true; // if we can get through all that, we know the port is open
            			} catch (UnsupportedCommOperationException e) {}       			
            		}
        		}
		}
	}
	
	public void serialEvent(SerialPortEvent event) {
		switch(event.getEventType()) {
			case SerialPortEvent.BI:
				System.out.print("BI\n");
			case SerialPortEvent.OE:
				System.out.print("OE\n");
			case SerialPortEvent.FE:
				System.out.print("FE\n");
			case SerialPortEvent.PE:
				System.out.print("PE\n");
			case SerialPortEvent.CD:
				System.out.print("CD\n");
			case SerialPortEvent.CTS:
				System.out.print("CTS\n");
			case SerialPortEvent.DSR:
				System.out.print("DSR\n");
			case SerialPortEvent.RI:
				System.out.print("RI\n");
			case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
				System.out.print("Out Buff Empty\n");
				break;
			case SerialPortEvent.DATA_AVAILABLE:
				//waitForInput = false;
			    //System.out.print("Data Available\n");
			    //add databuffer code
				
				//byte numBytes;
			    byte[] readBuffer = new byte[20];
			    
			    try {
			    		while (inputStream.available() > 0) {
			    			//System.out.println("data is being recived.");
			    			numBytes = inputStream.read(readBuffer);
			    			//System.out.print("serial data stream : legnth " + numBytes + " bytes. ");
			    			//System.out.print("data ");
			    			for(int i=0; i < numBytes; i++) {
			    				if(numBytes < readBuffer.length) {
			    					serialValue = Utils.unsignedByteAsInt((int)readBuffer[i]);
			    					BlogBotShop.serialValue(serialValue);
			    					/*if (i == numBytes-1) { 
			    						System.out.println(serialValue);	
			    					} 
			    					else { 
			    						System.out.print(serialValue +",");
			    					}	*/    			
			    				}
			    			}
			    			
			    		}
			    } catch (IOException e) {
					System.out.print("Problem reading from SerialPort");				
				} 
			    
            		break;
        		}
    	}
	
	void closeSerialPort() {
		System.out.println("Closing Port");
		if (portOpen == false) return; // there is no point going through all this if the port isn't open!
		try {
			inputStream.close();
			outputStream.close();
			serialPort.close();
		}
		catch (Exception e) {
			System.out.println("Failed to Close Port : " + e);
		} 
	}

}
